module app.controller.api.SearchController;

import std.json;
import hunt.framework;
import app.repository.ArticleRepository;
import app.response.ResultMsg;
import app.utils.RespCodeEnun;
import app.model.Article;
import app.utils.Const;

class SearchController : Controller
{
    mixin MakeController;

    /**
    * 分页获取文章列表
    * @words    string    搜索关键字
    */
    @Action Response search(string words)
    {
        import std.random;
        import std.string;
        import std.datetime.systime;

        ArticleRepository articleRepository = new ArticleRepository();
        ResultMsg resultMsg = new ResultMsg();

        try
        {
            Article[] articles = articleRepository.searchArticle(words);

            JSONValue[] items;
            foreach (Article article; articles)
            {
                JSONValue item;
                item["id"] = article.id;
                item["title"] = article.title;
                item["desc"] = article.desc;
                item["view_count"] = article.viewCount;
                item["comment_count"] = article.commentCount;
                item["created_at"] = tr(SysTime(unixTimeToStdTime(article.createdAt))
                        .toISOExtString(), "T", " ");
                item["img"] = Const.imgs.choice();
                items ~= item;
            }

            resultMsg.code = RespCodeEnun.SUCCESS;
            resultMsg.msg = "success";
            resultMsg.data["data"] = items;
        }
        catch (Exception e)
        {
            this.response.setStatus(500);
            resultMsg.code = RespCodeEnun.ERROR;
            resultMsg.msg = "系统错误";
        }

        return new JsonResponse(resultMsg);
    }
}
